<template>
  <div>
    <div>
      <van-nav-bar title="标题" left-text="返回" right-text="按钮" left-arrow @click-left="onClickLeft"
        @click-right="onClickRight" />
    </div>
    <div class="container">
      <van-scrollbar>
        <div v-for="(item, index) in messageList" :key="index">
          {{item.name}} : {{ item.text }}
        </div>
      </van-scrollbar>
    </div>
    <div style="margin-top: 20px;">
      <van-cell-group inset>
        <van-field v-model="message" rows="1" autosize type="textarea" placeholder="请输入" />
      </van-cell-group>
      <div @click="sendMessage">
        <van-button style="margin-left: 70%;" type="primary" size="normal">发送</van-button>
      </div>

    </div>
  </div>
</template>
  
<script setup>
import io from "socket.io-client";
import { reactive, ref, onMounted, onUnmounted } from 'vue'
import { showToast, showNotify } from 'vant';
import { PageParamsStore } from "../store";
const store = PageParamsStore();
const key = ref(store.key)
const socket = ref(null); //socket连接地址
const messageList = reactive([]); //聊天记录数组
const onClickLeft = () => history.back();
const onClickRight = () => showToast('按钮');
const message = ref('') //输入消息
let userData = JSON.parse(localStorage.getItem('userData'))

/**
 * 发送消息事件
 */
const sendMessage = () => {
  console.log("发送");
  // 发送消息到服务器
  socket.value.emit('chat', message.value);
}

onMounted(() => {
  // 连接到 Socket.IO 服务器
  socket.value = io('http://127.0.0.1:9002', {
    query: {
      roomId: key.value //携带房间标识
    },
    transports: ["websocket"], //取消websocket长轮询
    reconnectionDelay: 5000, //重连延迟时间为1秒，
    reconnectionAttempts: 3 //最多尝试重连3次
  });
  //连接初始化时
  socket.value.on('strat', message => {
    console.log(message);
  })
  // 监听 'chat' 事件，接收服务器发送的消息
  socket.value.on('chat', message => {
    console.log(message);
    messageList.push({
      id: null,
      date: Date.now(),
      text: message,
      name: userData.name,
      });
    console.log(messageList);
  });

  //加入当前选择的房间
  socket.value.emit('joinRoom', key.value);
})
onUnmounted(() => {
  if (socket.value) {
    //断开与socket.io服务器的连接
    socket.value.disconnect();
    socket.value = null;
  }
})



</script>
<style>
.container {
  height: 600px;
  /* 设置容器高度 */
  overflow: auto;
  /* 设置容器为可滚动 */
}
</style>